package autohome.wz.job;

import autohome.wz.lib.AutoHomeNewsHelper;
import autohome.wz.lib.Common;
import autohome.wz.lib.HttpRequest;
import autohome.wz.model.AutoHomeNews;
import autohome.wz.model.AutoNews.ArticleList;
import autohome.wz.model.AutoNews.NewsDetail;
import autohome.wz.model.AutoNews.NewsListResult;
import autohome.wz.model.AutoNews.NewsSection;
import autohome.wz.model.BaseApiResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with Administrator
 * DATE:2016/12/28
 * Time:10:24
 */
public class AutoNewsJob implements Job {


    //private static String listUrl = "http://cms.api.autohome.com.cn/baseapi/articles/articlelist.ashx?_appid=m&class1=44&pageindex=1&pagesize=20";

    private static List<NewsSection> listNews = new ArrayList<NewsSection>();

    private static int currentPage = 1;
    private static int totalPage = 0;
    private static Logger logger = Logger.getLogger(AutoNewsJob.class);

    public void execute(JobExecutionContext arg0) {
        if (listNews.size() == 0) {
            init();
        }
        LoadData();

    }

    public static void main(String[] args) {
        if (listNews.size() == 0) {
            init();
        }
        LoadData();
    }

    private static void init() {
        SAXReader reader = new SAXReader();
        try {
            URL url = AutoClubJob.class.getResource("/conf/AutoNewsConfig.xml");
            String path = url.getPath();
            Document document = reader.read(new File(path));
            Element root = document.getRootElement();
            @SuppressWarnings("unchecked")
            List<Element> childElements = root.elements();
            for (Element child : childElements
                    ) {
                int id = Integer.parseInt(child.attributeValue("id"));
                int state = Integer.parseInt(child.attributeValue("state"));
                String name = child.getText();
                if (state == 0) {
                    NewsSection newsSection = new NewsSection();
                    newsSection.setId(id);
                    newsSection.setSectionName(name);
                    newsSection.setState(state);
                    listNews.add(newsSection);
                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    private static void LoadData() {
        if (listNews.size() > 0) {
            for (NewsSection news : listNews) {
                if (news.getState() == 0) {
                    int newsId = news.getId();
                    //String className = news.getSectionName();
                    currentPage = 1;
                    totalPage = 0;
                    GetSection(newsId);
                }

            }
        }

    }


    private static void GetSection(int classId) {
        String url = "http://cms.api.autohome.com.cn/baseapi/articles/articlelist.ashx";
        String param = String.format("_appid=m&class1=%s&page=%s&pagesize=20", classId, currentPage);
        String strResult = HttpRequest.sendGet(url, param);
        if (!strResult.equals("")) {
            Gson gson = new Gson();
            BaseApiResult<NewsListResult> apiResult;
            try {
                apiResult = gson.fromJson(strResult, new TypeToken<BaseApiResult<NewsListResult>>() {
                }.getType());
                if (apiResult != null) {

                    totalPage = apiResult.getResult().getPageinfo().getPagecount();
                    if (totalPage > 500) {
                        totalPage = 500;
                    }
                    if (apiResult.getResult().getArticlelist().size() > 0) {
                        List<ArticleList> list = apiResult.getResult().getArticlelist();
                        for (ArticleList article : list) {
                            long newsId = article.getId();
                            String title = article.getTitle();
                            String author = article.getAuthor();
                            String pubDate = article.getPublishtime();
                            String summary = article.getSummary();
                            if (!pubDate.equals("")) {
                                pubDate = pubDate.substring(6, 19);
                            }
                            pubDate = Common.stampToDate(pubDate);
                            int days = Common.differenceDay(pubDate);
                            if (days <= 7) {
                                String content = article.getContent();
                                String contentClass = article.getClass1name();
                                String tags = article.getClass2name();
                                String img = article.getImg();

                                NewsDetail nd = GetNewDetail(newsId);
                                String series = nd.getSeriesIds();
                                if (series != null && series.length() > 0) {
                                    series = series.split(",")[0];
                                } else {
                                    series = "";
                                }

                                AutoHomeNews model = new AutoHomeNews();
                                model.setAuthor(author);
                                model.setBiz_id(newsId);
                                model.setTitle(title);
                                model.setCms_content_class(contentClass);
                                model.setBiz_type(1);
                                model.setCms_tags(tags);
                                model.setImg_url(img);
                                model.setContent(content);
                                model.setIndex_detail(summary);
                                model.setCms_series_id(series);
                                model.setPublish_time(Common.GetSqlTimeSpan(pubDate));
                                Add(model);
                            }
                            currentPage++;
                            if (currentPage < totalPage) {
                                GetSection(classId);
                            }
                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private static NewsDetail GetNewDetail(long newsId) {
        NewsDetail newsDetail = new NewsDetail();
        String url = "http://cms.api.autohome.com.cn/baseapi/articles/articledetails.ashx";
        String param = String.format("newid=%s&pageindex=1&_appid=app", newsId);
        String strResult = HttpRequest.sendGet(url, param);
        if (!strResult.equals("")) {
            BaseApiResult<NewsDetail> apiResult;
            try {
                Gson gson = new Gson();
                apiResult = gson.fromJson(strResult, new TypeToken<BaseApiResult<NewsDetail>>() {
                }.getType());
                if (apiResult != null) {
                    newsDetail = apiResult.getResult();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return newsDetail;
    }


    private static void Add(AutoHomeNews model) {
        int result = AutoHomeNewsHelper.Add(model);
        if (result > 0) {
            Common.showMessage(model.getTitle() + "入库成功");
        }

    }

}
